﻿using EcoSystem.Office.Enums;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace EcoSystem.Office.Word
{
    public class MailMergeHelper
    {
        public FormMergeData ModelToMergeFields(object model)
        {
            if (model is FormMergeData)
            {
                return (FormMergeData)model;
            }

            FormMergeData list = new FormMergeData();
            if (model.GetType() == typeof(Dictionary<string, object>))
            {
                var dict = (Dictionary<string, object>)model;
                foreach (var item in dict)
                {
                    var type = item.Value != null ? item.Value.GetType() : typeof(string);
                    list.Add(GetFormMergeField(item.Key, type, item.Value));
                }
            }
            else
            {
                var arrs = model.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField);
                foreach (var p in arrs)
                {
                    list.Add(GetFormMergeField(p.Name, p.PropertyType, p.GetValue(model)));
                }
            }
            return list;
        }

        private static Type[] basicTypes = new Type[] { typeof(string), typeof(DateTime), typeof(decimal) };

        private FormMergeField GetFormMergeField(string name, Type type, object value)
        {
            if (type.IsEnum)
            {
                return new FormMergeField()
                {
                    Name = name,
                    Type = FormFieldType.Text,
                    Value = EnumHelper.GetEnumAtribute(value)
                };
            }
            else if (type.IsPrimitive || basicTypes.Contains(type))
            {
                return new FormMergeField()
                {
                    Name = name,
                    Type = FormFieldType.Text,
                    Value = value
                };
            }
            else if (type == typeof(Image) || type == typeof(Bitmap) || type == typeof(byte[]))
            {
                return new FormMergeField()
                {
                    Name = name,
                    Type = FormFieldType.Image,
                    Value = value,
                };
            }
            else if (type == typeof(ImageField))
            {
                var img = (ImageField)value;

                object data = img.ImageData;
                if (img.Image != null)
                {
                    data = img.Image;
                }
                return new FormMergeField()
                {
                    Name = name,
                    Type = FormFieldType.Image,
                    Value = data,
                    ImageOptions = img.Options
                };
            }
            else
            {
                if (typeof(IList).IsAssignableFrom(type))
                {
                    //数组及List
                    Type t = type.GetElementType();
                    var childrenList = new List<FormMergeData>();
                    var clist = (IList)value;
                    if (clist != null)
                    {
                        foreach (var cItem in clist)
                        {
                            childrenList.Add(ModelToMergeFields(cItem));
                        }
                    }
                    return new FormMergeField()
                    {
                        Name = name,
                        Type = FormFieldType.Complex,
                        Value = childrenList
                    };
                }
                else
                {
                    //对象
                    var childForm = ModelToMergeFields(value);
                    childForm.Name = name;
                    return new FormMergeField()
                    {
                        Name = name,
                        Type = FormFieldType.Complex,
                        Value = childForm,
                    };
                }
            }
        }

        public DataTable FormMergeToTable(List<FormMergeData> list, string tableName = null)
        {
            if (list == null || list.Count == 0)
            {
                throw new ArgumentException("参数错误，要转换的列表不能为空且行数必须大于0");
            }
            DataTable dt = new DataTable();
            FormMergeData first = list.First();
            foreach (var c in first)
            {
                dt.Columns.Add(c.Name, c.Value?.GetType());
            }
            foreach (var item in list)
            {
                DataRow dr = dt.NewRow();
                foreach (DataColumn col in dt.Columns)
                {
                    var c = item.FirstOrDefault(s => s.Name == col.ColumnName && s.Type != FormFieldType.Complex);
                    if (c != null)
                    {
                        dr[c.Name] = c.Value;
                    }
                }
                dt.Rows.Add(dr);
            }
            dt.AcceptChanges();
            return dt;
        }

        public byte[] GetImageData(FormMergeField field)
        {
            if (field == null)
            {
                return null;
            }
            else if (field.Value is byte[])
            {
                return (byte[])field.Value;
            }
            else if (field.Value is Image)
            {
                var image = (Image)field.Value;
                using (var ms = new MemoryStream())
                {
                    image.Save(ms, ImageFormat.Jpeg);
                    return ms.ToArray();
                }
            }
            return null;
        }
    }
}
